﻿// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.


using Bit.Art.Sso.Db;
using IdentityModel;
using IdentityServer4.EntityFramework.DbContexts;
using IdentityServer4.EntityFramework.Interfaces;
using IdentityServer4.EntityFramework.Mappers;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Linq;
using System.Security.Claims;

namespace Bit.Art.Sso
{
    public class SeedData
    {
        public static void EnsureSeedData(IServiceProvider serviceProvider)
        {
            using (var scope = serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope())
            {
                var userContext = scope.ServiceProvider.GetService<ApplicationUserDbContext>();
                userContext.Database.Migrate();

                scope.ServiceProvider.GetService<PersistedGrantDbContext>().Database.Migrate();

                var context = scope.ServiceProvider.GetService<ConfigurationDbContext>();
                context.Database.Migrate();
                EnsureSeedData(context);

                var userManager = scope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
                EnsureSeedUserData(userContext, userManager);
            }
        }

        private static void EnsureSeedUserData(ApplicationUserDbContext context, UserManager<ApplicationUser> manager)
        {
            var user = new ApplicationUser()
            {
                UserName = "shiyimin"
            };
            var result = manager.CreateAsync(user, "Pass123$").Result;

            result = manager.AddClaimsAsync(user, new Claim[]{
                        new Claim(JwtClaimTypes.Name, "Shi Yimin"),
                        new Claim(JwtClaimTypes.GivenName, "Yimin"),
                        new Claim(JwtClaimTypes.FamilyName, "Shi"),
                        new Claim(JwtClaimTypes.Email, "shiyimin@vowei.com"),
                        new Claim(JwtClaimTypes.EmailVerified, "true", ClaimValueTypes.Boolean),
                        new Claim(JwtClaimTypes.WebSite, "http://www.vowei.com"),
                        new Claim(JwtClaimTypes.PhoneNumber, "18621519910"),
                        new Claim(JwtClaimTypes.NickName, "施懿民"),
                        new Claim(JwtClaimTypes.Picture, "http://www.vowei.com")
                    }).Result;
        }

        private static void EnsureSeedData(IConfigurationDbContext context)
        {
            Console.WriteLine("Seeding database...");

            if (!context.Clients.Any())
            {
                Console.WriteLine("Clients being populated");
                foreach (var client in Config.GetClients().ToList())
                {
                    context.Clients.Add(client.ToEntity());
                }
                context.SaveChanges();
            }
            else
            {
                Console.WriteLine("Clients already populated");
            }

            if (!context.IdentityResources.Any())
            {
                Console.WriteLine("IdentityResources being populated");
                foreach (var resource in Config.GetIdentityResources().ToList())
                {
                    context.IdentityResources.Add(resource.ToEntity());
                }
                context.SaveChanges();
            }
            else
            {
                Console.WriteLine("IdentityResources already populated");
            }

            if (!context.ApiResources.Any())
            {
                Console.WriteLine("ApiResources being populated");
                foreach (var resource in Config.GetApis().ToList())
                {
                    context.ApiResources.Add(resource.ToEntity());
                }
                context.SaveChanges();
            }
            else
            {
                Console.WriteLine("ApiResources already populated");
            }
            
            Console.WriteLine("Done seeding database.");
            Console.WriteLine();
        }
    }
}
